```vue
<template>
  <div class="vm-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon> 创建虚拟机
      </el-button>
      <el-button-group>
        <el-button :disabled="!selectedVM" @click="startVM">
          <el-icon><VideoPlay /></el-icon> 启动
        </el-button>
        <el-button :disabled="!selectedVM" @click="stopVM">
          <el-icon><VideoPause /></el-icon> 停止
        </el-button>
        <el-button :disabled="!selectedVM" @click="restartVM">
          <el-icon><Refresh /></el-icon> 重启
        </el-button>
      </el-button-group>
      <el-button-group>
        <el-button :disabled="!selectedVM || !canMigrate" @click="showMigrateDialog">
          <el-icon><Connection /></el-icon> 迁移
        </el-button>
        <el-button :disabled="!selectedVM" type="danger" @click="deleteVM">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
      </el-button-group>
      
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索虚拟机（名称/ID/节点）"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 任务进度提示 -->
    <el-progress
      v-if="taskProgress > 0 && taskProgress < 100"
      :percentage="taskProgress"
      :text-inside="true"
      :stroke-width="20"
      style="margin-bottom: 20px;"
    >
      <span>{{ taskMessage }}</span>
    </el-progress>

    <!-- 虚拟机列表 -->
    <el-table
      :data="filteredVMList"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="120" sortable />
      <el-table-column prop="name" label="名称" width="180" sortable>
        <template #default="{row}">
          <el-tag v-if="row.isTemplate" type="info">模板</el-tag>
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="node" label="节点" width="120" />
      <el-table-column label="资源配置" width="220">
        <template #default="{row}">
          <div class="resource-info">
            <span><el-icon><Cpu /></el-icon> {{ row.cpu }}核</span>
            <span><el-icon><Memory /></el-icon> {{ row.memory }}GB</span>
            <span><el-icon><HardDisk /></el-icon> {{ row.disk }}GB</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="IP地址" width="150" />
      <el-table-column prop="os" label="操作系统" width="150" />
      <el-table-column prop="createdAt" label="创建时间" width="180" sortable />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="showDetail(row)">详情</el-button>
          <el-button size="small" @click="showConsole(row)">控制台</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalVMs"
        layout="total, sizes, prev, pager, next, jumper"
        @update:current-page="currentPage = $event"
        @update:page-size="pageSize = $event"
        @size-change="fetchVMList"
        @current-change="fetchVMList"
      />
    </div>

    <!-- 创建虚拟机对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建虚拟机" width="50%">
      <el-form :model="newVMForm" label-width="120px" :rules="vmRules" ref="vmFormRef">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基础配置" name="basic">
            <el-form-item label="虚拟机名称" prop="name">
              <el-input v-model="newVMForm.name" placeholder="请输入虚拟机名称" />
            </el-form-item>
            
            <el-form-item label="选择ISO文件" prop="iso">
              <el-select v-model="newVMForm.iso" placeholder="请选择ISO文件" filterable>
                <el-option
                  v-for="iso in isos"
                  :key="iso.id"
                  :label="`${iso.name} (${Object.keys(iso.paths).length} 个节点可用)`"
                  :value="iso.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="目标节点" prop="node">
              <el-select v-model="newVMForm.node" placeholder="请选择目标节点" filterable>
                <el-option
                  v-for="node in nodes"
                  :key="node.id"
                  :label="`${node.name} (${node.status})`"
                  :value="node.id"
                  :disabled="node.status !== '正常'"
                />
              </el-select>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="资源配置" name="resource">
            <el-form-item label="CPU核心数" prop="cpu">
              <el-input-number v-model="newVMForm.cpu" :min="1" :max="32" />
            </el-form-item>
            
            <el-form-item label="内存(GB)" prop="memory">
              <el-input-number v-model="newVMForm.memory" :min="1" :max="256" />
            </el-form-item>
            
            <el-form-item label="磁盘大小(GB)" prop="disk">
              <el-input-number v-model="newVMForm.disk" :min="10" :max="2048" />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="网络配置" name="network">
            <el-form-item label="网络类型" prop="networkType">
              <el-select v-model="newVMForm.networkType" placeholder="请选择网络类型">
                <el-option label="NAT" value="nat" />
                <el-option label="桥接" value="bridge" />
                <el-option label="私有网络" value="private" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="IP地址" prop="ip" v-if="newVMForm.networkType !== 'nat'">
              <el-input v-model="newVMForm.ip" placeholder="请输入IP地址（如192.168.1.100）" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createVM">创建</el-button>
      </template>
    </el-dialog>

    <!-- 迁移虚拟机对话框 -->
    <el-dialog v-model="migrateDialogVisible" title="迁移虚拟机" width="40%">
      <el-form :model="migrateForm" label-width="120px" :rules="migrateRules" ref="migrateFormRef">
        <el-form-item label="虚拟机名称">
          <el-input v-model="migrateForm.vmName" disabled />
        </el-form-item>
        
        <el-form-item label="当前节点">
          <el-input v-model="migrateForm.currentNode" disabled />
        </el-form-item>
        
        <el-form-item label="目标节点" prop="targetNode">
          <el-select v-model="migrateForm.targetNode" placeholder="请选择目标节点" filterable>
            <el-option
              v-for="node in availableNodes"
              :key="node.id"
              :label="`${node.name} (CPU: ${node.cpuUsage}%, 内存: ${node.memoryUsage}%)`"
              :value="node.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="迁移类型" prop="type">
          <el-radio-group v-model="migrateForm.type">
            <el-radio label="cold">冷迁移（关机迁移）</el-radio>
            <el-radio label="live" :disabled="!supportsLiveMigration">热迁移（在线迁移）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="resourceWarning.message">
          <el-alert
            :type="resourceWarning.type"
            :title="resourceWarning.message"
            :closable="false"
            show-icon
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="migrateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMigrate">开始迁移</el-button>
      </template>
    </el-dialog>

    <!-- 虚拟机详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="`虚拟机详情 - ${currentVM?.name || ''}`" width="60%">
      <el-descriptions :column="2">
        <el-descriptions-item label="ID">{{ currentVM?.id }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ currentVM?.name }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentVM?.status)">
            {{ currentVM?.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="所在节点">{{ currentVM?.node }}</el-descriptions-item>
        <el-descriptions-item label="CPU">{{ currentVM?.cpu }} 核</el-descriptions-item>
        <el-descriptions-item label="内存">{{ currentVM?.memory }} GB</el-descriptions-item>
        <el-descriptions-item label="磁盘">{{ currentVM?.disk }} GB</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentVM?.ip || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="操作系统">{{ currentVM?.os || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentVM?.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="最后启动时间">{{ currentVM?.lastStartedAt || 'N/A' }}</el-descriptions-item>
      </el-descriptions>
      <el-tabs type="border-card" class="detail-tabs">
        <el-tab-pane label="性能监控">
          <div v-if="!currentVM?.metricsHistory" class="no-data-container">
            <el-empty description="暂无性能监控数据" />
          </div>
          <template v-else>
            <div class="monitor-chart" ref="cpuChart"></div>
            <div class="monitor-chart" ref="memoryChart"></div>
            <div class="monitor-chart" ref="diskChart"></div>
            <div class="monitor-chart" ref="networkChart"></div>
          </template>
        </el-tab-pane>
        
        <el-tab-pane label="快照管理">
          <div class="snapshot-actions">
            <el-button type="primary" @click="showCreateSnapshotDialog">
              <el-icon><Plus /></el-icon> 创建快照
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedSnapshot" 
              @click="deleteSnapshot"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
            <el-button 
              type="warning" 
              :disabled="!selectedSnapshot" 
              @click="revertSnapshot"
            >
              <el-icon><Refresh /></el-icon> 回滚
            </el-button>
          </div>
          
          <el-table 
            :data="snapshots" 
            style="margin-top: 20px;"
            @selection-change="handleSnapshotSelection"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="快照名称" width="180" />
            <el-table-column prop="createdAt" label="创建时间" width="180" />
            <el-table-column prop="state" label="状态" width="120">
              <template #default="{row}">
                <el-tag :type="row.state === 'running' ? 'success' : 'info'">
                  {{ row.state }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
          </el-table>
        </el-tab-pane>

        <!-- 创建快照对话框 -->
        <el-dialog v-model="snapshotDialogVisible" title="创建快照">
          <el-form :model="snapshotForm" label-width="120px" :rules="snapshotRules">
            <el-form-item label="快照名称" prop="name">
              <el-input v-model="snapshotForm.name" placeholder="请输入快照名称" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input 
                v-model="snapshotForm.description" 
                type="textarea" 
                placeholder="请输入快照描述"
              />
            </el-form-item>
            <el-form-item label="内存状态" prop="includeMemory">
              <el-switch v-model="snapshotForm.includeMemory" />
              <span class="form-tip">包含内存状态（创建后虚拟机将暂停）</span>
            </el-form-item>
            <el-form-item label="原子性" prop="atomic">
              <el-switch v-model="snapshotForm.atomic" />
              <span class="form-tip">原子性快照（确保一致性）</span>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <el-button @click="snapshotDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmCreateSnapshot">创建</el-button>
          </template>
        </el-dialog>
        
        <el-tab-pane label="操作日志">
          <div class="log-filter">
            <el-select 
              v-model="logFilter.action" 
              placeholder="筛选操作类型" 
              clearable
              style="width: 200px; margin-right: 10px;"
            >
              <el-option label="全部操作" value="" />
              <el-option label="创建" value="vm_create" />
              <el-option label="启动" value="vm_start" />
              <el-option label="停止" value="vm_stop" />
              <el-option label="重启" value="vm_restart" />
              <el-option label="删除" value="vm_delete" />
              <el-option label="迁移" value="vm_migrate" />
              <el-option label="快照创建" value="create_snapshot" />
              <el-option label="快照回滚" value="revert_snapshot" />
              <el-option label="快照删除" value="delete_snapshot" />
            </el-select>
            
            <el-select
              v-model="logFilter.status"
              placeholder="筛选状态"
              clearable
              style="width: 120px; margin-right: 10px;"
            >
              <el-option label="全部状态" value="" />
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
            </el-select>
            
            <el-date-picker
              v-model="logFilter.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="timestamp"
              style="width: 350px;"
            />
            
            <el-button 
              type="primary" 
              @click="fetchVMLogs"
              :loading="logLoading"
            >
              查询
            </el-button>
          </div>
          
          <el-table 
            :data="vmLogs" 
            style="width: 100%; margin-top: 15px;"
            v-loading="logLoading"
            stripe
            height="400"
          >
            <el-table-column prop="timestamp" label="时间" width="180">
              <template #default="{row}">
                {{ new Date(row.timestamp * 1000).toLocaleString() }}
              </template>
            </el-table-column>
            
            <el-table-column prop="action" label="操作类型" width="150">
              <template #default="{row}">
                <el-tag :type="getActionTagType(row.action)">
                  {{ getActionLabel(row.action) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="user" label="操作人" width="120" />
            
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{row}">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="execution_time" label="耗时(秒)" width="100">
              <template #default="{row}">
                {{ row.execution_time ? row.execution_time.toFixed(2) : '-' }}
              </template>
            </el-table-column>
            
            <el-table-column label="详情">
              <template #default="{row}">
                <el-popover trigger="hover" width="auto">
                  <template #reference>
                    <el-button type="text">查看详情</el-button>
                  </template>
                  <div style="max-width: 500px;">
                    <p v-if="row.error"><strong>错误信息:</strong> {{ row.error }}</p>
                    <pre v-if="row.details">{{ JSON.stringify(row.details, null, 2) }}</pre>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              :current-page="logPagination.page"
              :page-size="logPagination.size"
              :total="logPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="fetchVMLogs"
              @size-change="handleLogSizeChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import request from '@/utils/request'

const vmList = ref([])
const filteredVMList = ref([])
const selectedVM = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalVMs = ref(0)
const searchQuery = ref('')
const loading = ref(false)
const taskProgress = ref(0)
const taskMessage = ref('')
const taskInterval = ref(null)

const createDialogVisible = ref(false)
const migrateDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const activeTab = ref('basic')
const snapshotDialogVisible = ref(false)
const selectedSnapshot = ref(null) 

const newVMForm = reactive({
  name: '',
  iso: '',
  node: '',
  cpu: 2,
  memory: 4,
  disk: 50,
  networkType: 'nat',
  ip: ''
})

const migrateForm = reactive({
  vmId: '',
  vmName: '',
  currentNode: '',
  targetNode: '',
  type: 'cold'
})

const resourceWarning = reactive({
  type: 'info',
  message: ''
})

const currentVM = ref(null)
const snapshots = ref([])
const operationLogs = ref([])

const isos = ref([])
const nodes = ref([])

const vmRules = reactive({
  name: [
    { required: true, message: '请输入虚拟机名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在3到50个字符', trigger: 'blur' }
  ],
  iso: [
    { required: true, message: '请选择ISO文件', trigger: 'change' }
  ],
  node: [
    { required: true, message: '请选择目标节点', trigger: 'change' }
  ],
  cpu: [
    { required: true, message: '请设置CPU核心数', trigger: 'blur' },
    { type: 'number', min: 1, max: 32, message: 'CPU核心数需在1到32之间', trigger: 'blur' }
  ],
  memory: [
    { required: true, message: '请设置内存大小', trigger: 'blur' },
    { type: 'number', min: 1, max: 256, message: '内存大小需在1到256GB之间', trigger: 'blur' }
  ],
  disk: [
    { required: true, message: '请设置磁盘大小', trigger: 'blur' },
    { type: 'number', min: 10, max: 2048, message: '磁盘大小需在10到2048GB之间', trigger: 'blur' }
  ],
  networkType: [
    { required: true, message: '请选择网络类型', trigger: 'change' }
  ],
  ip: [
    {
      validator: (rule, value, callback) => {
        if (newVMForm.networkType !== 'nat' && !value) {
          callback(new Error('桥接或私有网络需要指定IP地址'))
        } else if (value && !/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(value)) {
          callback(new Error('请输入有效的IP地址（如192.168.1.100）'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const migrateRules = reactive({
  targetNode: [
    { required: true, message: '请选择目标节点', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择迁移类型', trigger: 'change' }
  ]
})

const availableNodes = computed(() => {
  return nodes.value.filter(node => 
    node.id !== migrateForm.currentNode && 
    node.status === '正常'
  )
})

const supportsLiveMigration = computed(() => {
  return selectedVM.value?.status === 'running'
})

const canMigrate = computed(() => {
  return selectedVM && !selectedVM.value?.isTemplate
})

const vmFormRef = ref(null)
const migrateFormRef = ref(null)

const vmLogs = ref([])
const logLoading = ref(false)
const logFilter = reactive({
  action: '',
  status: '',
  dateRange: []
})
const logPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const actionLabels = {
  'vm_create': '创建虚拟机',
  'vm_start': '启动',
  'vm_stop': '停止',
  'vm_restart': '重启',
  'vm_delete': '删除',
  'vm_migrate': '迁移',
  'create_snapshot': '创建快照',
  'revert_snapshot': '回滚快照',
  'delete_snapshot': '删除快照'
}

const actionColors = {
  'vm_create': '',
  'vm_start': 'success',
  'vm_stop': 'warning',
  'vm_restart': 'primary',
  'vm_delete': 'danger',
  'vm_migrate': 'info',
  'create_snapshot': '',
  'revert_snapshot': 'primary',
  'delete_snapshot': 'danger'
}

const fetchVMList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/vms', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: searchQuery.value
      }
    })
    
    // 为每个VM添加实时资源使用数据
    const vmsWithMetrics = await Promise.all(res.data.items.map(async vm => {
      try {
        const metricsRes = await request.get(`/api/vms/${vm.id}/metrics`)
        return {
          ...vm,
          metrics: metricsRes.data
        }
      } catch (error) {
        return vm // 如果获取指标失败，返回原始VM数据
      }
    }))
    
    vmList.value = vmsWithMetrics
    filteredVMList.value = vmsWithMetrics
    totalVMs.value = res.data.total
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取虚拟机列表失败')
  } finally {
    loading.value = false
  }
}

const fetchNodesAndISOs = async () => {
  try {
    const [nodesRes, isosRes] = await Promise.all([
      request.get('/api/nodes'),
      request.get('/api/isos')
    ])
    nodes.value = nodesRes.data.items
    isos.value = isosRes.data.items
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取节点或ISO文件信息失败')
  }
}

const handleSelectionChange = (selection) => {
  selectedVM.value = selection.length > 0 ? selection[0] : null
}

const handleSearch = () => {
  if (searchQuery.value) {
    filteredVMList.value = vmList.value.filter(vm => 
      vm.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      vm.id.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      vm.node.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  } else {
    filteredVMList.value = vmList.value
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 'running': return 'success'
    case 'stopped': return 'danger'
    case 'paused': return 'warning'
    case 'template': return 'info'
    default: return ''
  }
}

const pollTaskStatus = async (taskId) => {
  taskProgress.value = 0
  taskMessage.value = '任务初始化...'
  
  taskInterval.value = setInterval(async () => {
    try {
      const res = await request.get(`/api/tasks/${taskId}`)
      const { status, progress, message, result } = res.data
      
      taskProgress.value = progress || 0
      taskMessage.value = message || '处理中...'
      
      if (status === 'SUCCESS') {
        clearInterval(taskInterval.value)
        taskProgress.value = 100
        taskMessage.value = result.message || '任务完成'
        ElMessage.success(result.message || '任务完成')
        setTimeout(() => {
          taskProgress.value = 0
          taskMessage.value = ''
          fetchVMList()
        }, 2000)
      } else if (status === 'FAILURE') {
        clearInterval(taskInterval.value)
        taskProgress.value = 0
        taskMessage.value = ''
        ElMessage.error(result.message || '任务失败')
      }
    } catch (error) {
      clearInterval(taskInterval.value)
      taskProgress.value = 0
      taskMessage.value = ''
      ElMessage.error(error.response?.data?.message || '获取任务状态失败')
    }
  }, 2000)
}

const showCreateDialog = () => {
  createDialogVisible.value = true
  resetVMForm()
}

const resetVMForm = () => {
  newVMForm.name = ''
  newVMForm.iso = ''
  newVMForm.node = ''
  newVMForm.cpu = 2
  newVMForm.memory = 4
  newVMForm.disk = 50
  newVMForm.networkType = 'nat'
  newVMForm.ip = ''
  if (vmFormRef.value) {
    vmFormRef.value.resetFields()
  }
}

const checkTargetNodeResources = async () => {
  if (!migrateForm.targetNode || !selectedVM.value) {
    resourceWarning.type = 'info'
    resourceWarning.message = ''
    return
  }

  try {
    const targetNode = nodes.value.find(node => node.id === migrateForm.targetNode)
    if (!targetNode) {
      resourceWarning.type = 'error'
      resourceWarning.message = '目标节点不可用'
      return
    }

    const requiredCpu = selectedVM.value.cpu
    const requiredMemory = selectedVM.value.memory
    const availableCpu = 100 - targetNode.cpuUsage
    const availableMemory = 100 - targetNode.memoryUsage

    if (availableCpu < requiredCpu * 10 || availableMemory < requiredMemory * 10) {
      resourceWarning.type = 'warning'
      resourceWarning.message = '目标节点资源可能不足，但您可以继续迁移'
    } else {
      resourceWarning.type = 'success'
      resourceWarning.message = '目标节点资源充足'
    }
  } catch (error) {
    resourceWarning.type = 'error'
    resourceWarning.message = '资源检查失败，但您可以继续迁移'
  }
}

const showMigrateDialog = () => {
  if (!selectedVM.value) return
  
  migrateForm.vmId = selectedVM.value.id
  migrateForm.vmName = selectedVM.value.name
  migrateForm.currentNode = selectedVM.value.node
  migrateForm.targetNode = ''
  migrateForm.type = selectedVM.value.status === 'running' ? 'live' : 'cold'
  
  resourceWarning.type = 'info'
  resourceWarning.message = ''
  
  migrateDialogVisible.value = true
}

const showDetail = async (vm) => {
  currentVM.value = vm
  detailDialogVisible.value = true
  
  // 获取虚拟机详细指标
  try {
    const metricsRes = await request.get(`/api/vms/${vm.id}/metrics`)
    currentVM.value.metrics = metricsRes.data
    
    // 获取历史性能数据
    const historyRes = await request.get(`/api/vms/${vm.id}/metrics/history`)
    if (historyRes.data && historyRes.data.timestamps) {
      currentVM.value.metricsHistory = historyRes.data
      nextTick(() => {
        initCharts()
      })
    }
    
    // 获取操作日志
    fetchVMLogs()
    
    // 获取快照列表
    fetchSnapshots()
  } catch (error) {
    ElMessage.error('获取虚拟机详情失败')
  }
}

const showConsole = (vm) => {
  ElMessage.info(`正在连接到虚拟机 ${vm.name} 的控制台...`)
}

const initCharts = () => {
  const cpuChart = echarts.init(document.querySelector('.monitor-chart'))
  const memoryChart = echarts.init(document.querySelector('.monitor-chart:nth-child(2)'))
  const diskChart = echarts.init(document.querySelector('.monitor-chart:nth-child(3)'))
  const networkChart = echarts.init(document.querySelector('.monitor-chart:nth-child(4)'))
  
  if (!currentVM.value?.metricsHistory?.timestamps) {
    console.error('No valid history data available for charts')
    return
  }
  
  const history = currentVM.value.metricsHistory
  const timestamps = history.timestamps || []
  
  const commonOption = {
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { 
      type: 'category', 
      boundaryGap: false, 
      data: timestamps.map(t => new Date(t).toLocaleTimeString()) 
    }
  }
  
  cpuChart.setOption({
    ...commonOption,
    title: { text: 'CPU使用率 (%)', left: 'center' },
    yAxis: { type: 'value', max: 100 },
    series: [{ 
      name: 'CPU使用率', 
      type: 'line', 
      data: history.cpuUsage,
      areaStyle: { color: '#409EFF' },
      lineStyle: { color: '#409EFF' }
    }]
  })
  
  memoryChart.setOption({
    ...commonOption,
    title: { text: '内存使用率 (%)', left: 'center' },
    yAxis: { type: 'value', max: 100 },
    series: [{ 
      name: '内存使用率', 
      type: 'line', 
      data: history.memoryUsage,
      areaStyle: { color: '#67C23A' },
      lineStyle: { color: '#67C23A' }
    }]
  })
  
  diskChart.setOption({
    ...commonOption,
    title: { text: '磁盘IO (MB/s)', left: 'center' },
    yAxis: { type: 'value' },
    series: [
      { 
        name: '读取', 
        type: 'line', 
        data: history.diskRead,
        areaStyle: { color: '#E6A23C' },
        lineStyle: { color: '#E6A23C' }
      },
      { 
        name: '写入', 
        type: 'line', 
        data: history.diskWrite,
        areaStyle: { color: '#F56C6C' },
        lineStyle: { color: '#F56C6C' }
      }
    ]
  })
  
  networkChart.setOption({
    ...commonOption,
    title: { text: '网络流量 (KB/s)', left: 'center' },
    yAxis: { type: 'value' },
    series: [
      { 
        name: '接收', 
        type: 'line', 
        data: history.networkIn,
        areaStyle: { color: '#909399' },
        lineStyle: { color: '#909399' }
      },
      { 
        name: '发送', 
        type: 'line', 
        data: history.networkOut,
        areaStyle: { color: '#909399' },
        lineStyle: { color: '#909399' }
      }
    ]
  })
}

const createVM = async () => {
  try {
    await vmFormRef.value.validate()
    loading.value = true
    const res = await request.post('/api/vms', {
      name: newVMForm.name,
      iso: newVMForm.iso,
      node: newVMForm.node,
      cpu: newVMForm.cpu,
      memory: newVMForm.memory,
      disk: newVMForm.disk,
      networkType: newVMForm.networkType,
      ip: newVMForm.networkType !== 'nat' ? newVMForm.ip : undefined
    })
    
    if (res.status === 'success' && res.data.task_id) {
      createDialogVisible.value = false
      ElMessage.success('虚拟机创建任务已启动')
      pollTaskStatus(res.data.task_id)
    } else {
      ElMessage.error(res.data.message || '无法获取任务ID')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '创建虚拟机失败')
  } finally {
    loading.value = false
  }
}

const startVM = async () => {
  if (!selectedVM.value) return
  
  try {
    loading.value = true
    const res = await request.post(`/api/vms/${selectedVM.value.id}/start`)
    if (res.status === 'success' && res.data.task_id) {
      ElMessage.success('虚拟机启动任务已启动')
      pollTaskStatus(res.data.task_id)
    } else {
      ElMessage.error(res.data.message || '启动虚拟机失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '启动虚拟机失败')
  } finally {
    loading.value = false
  }
}

const stopVM = async () => {
  if (!selectedVM.value) return
  
  try {
    await ElMessageBox.confirm(`确定要停止虚拟机 ${selectedVM.value.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const res = await request.post(`/api/vms/${selectedVM.value.id}/stop`)
    if (res.status === 'success' && res.data.task_id) {
      ElMessage.success('虚拟机停止任务已启动')
      pollTaskStatus(res.data.task_id)
    } else {
      ElMessage.error(res.data.message || '停止虚拟机失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '停止虚拟机失败')
    }
  } finally {
    loading.value = false
  }
}

const restartVM = async () => {
  if (!selectedVM.value) return
  
  try {
    await ElMessageBox.confirm(`确定要重启虚拟机 ${selectedVM.value.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const res = await request.post(`/api/vms/${selectedVM.value.id}/restart`)
    if (res.status === 'success' && res.data.task_id) {
      ElMessage.success('虚拟机重启任务已启动')
      pollTaskStatus(res.data.task_id)
      setTimeout(() => {
        fetchVMList()
      }, 12000) 
    } else {
      ElMessage.error(res.data.message || '重启虚拟机失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '重启虚拟机失败')
    }
  } finally {
    loading.value = false
  }
}

const deleteVM = async () => {
  if (!selectedVM.value) return
  
  try {
    await ElMessageBox.confirm(`确定要删除虚拟机 ${selectedVM.value.name} 吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    loading.value = true
    const res = await request.delete(`/api/vms/${selectedVM.value.id}`)
    if (res.status === 'success' && res.data.task_id) {
      ElMessage.success('虚拟机删除任务已启动')
      pollTaskStatus(res.data.task_id)
    } else {
      ElMessage.error(res.data.message || '删除虚拟机失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除虚拟机失败')
    }
  } finally {
    loading.value = false
  }
}

const confirmMigrate = async () => {
  try {
    await migrateFormRef.value.validate()
    
    // 调试日志：确认迁移表单数据
    console.log('Migration Form Data:', {
      vmId: migrateForm.vmId,
      vmName: migrateForm.vmName,
      currentNode: migrateForm.currentNode,
      targetNode: migrateForm.targetNode,
      type: migrateForm.type
    })

    await ElMessageBox.confirm(
      `确定要将虚拟机 ${migrateForm.vmName} 迁移到新节点吗？${
        migrateForm.type === 'cold' ? '此操作将停止虚拟机运行' : '此操作将尝试保持虚拟机运行'
      }`,
      '确认迁移',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    // 构造请求体 - 修改这里的字段名
    const migratePayload = {
      targetNode: migrateForm.targetNode,  // 保持原样
      type: migrateForm.type               // 保持原样
    }
    console.log('Sending Migration Request:', migratePayload)
    
    const res = await request.post(`/api/vms/${migrateForm.vmId}/migrate`, migratePayload)
    
    console.log('Migration API Response:', res)
    
    if (res.status === 'success' && res.data.task_id) {
      migrateDialogVisible.value = false
      ElMessage.success('虚拟机迁移任务已启动')
      pollTaskStatus(res.data.task_id)
    } else {
      ElMessage.error(res.data.message || '无法获取任务ID')
    }
  } catch (error) {
    console.error('Migration Error:', error)
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '迁移虚拟机失败')
    }
  } finally {
    loading.value = false
  }
}

const snapshotForm = reactive({
  name: '',
  description: '',
  includeMemory: false,
  atomic: true
})

const snapshotRules = {
  name: [
    { required: true, message: '请输入快照名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在3到50个字符', trigger: 'blur' }
  ]
}
const handleSnapshotSelection = (selection) => {
  selectedSnapshot.value = selection.length > 0 ? selection[0] : null
}
const showCreateSnapshotDialog = () => {
  if (!currentVM.value) return
  snapshotForm.name = `snap-${new Date().toISOString().slice(0, 10)}`
  snapshotForm.description = ''
  snapshotForm.includeMemory = false
  snapshotForm.atomic = true
  snapshotDialogVisible.value = true
}

const confirmCreateSnapshot = async () => {
  try {
    loading.value = true
    const res = await request.post(`/api/vms/${currentVM.value.id}/snapshots`, snapshotForm)
    ElMessage.success(res.message || '快照创建成功')
    snapshotDialogVisible.value = false
    fetchSnapshots()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '创建快照失败')
  } finally {
    loading.value = false
  }
}

const deleteSnapshot = async () => {
  if (!selectedSnapshot.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除快照 "${selectedSnapshot.value.name}" 吗？此操作不可恢复！`,
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    loading.value = true
    const res = await request.delete(
      `/api/vms/${currentVM.value.id}/snapshots/${selectedSnapshot.value.name}`
    )
    ElMessage.success(res.message || '快照删除成功')
    fetchSnapshots()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除快照失败')
    }
  } finally {
    loading.value = false
  }
}

const revertSnapshot = async () => {
  if (!selectedSnapshot.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要回滚到快照 "${selectedSnapshot.value.name}" 吗？当前状态将丢失！`,
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    loading.value = true
    const res = await request.post(
      `/api/vms/${currentVM.value.id}/snapshots/${selectedSnapshot.value.name}/revert`
    )
    ElMessage.success(res.message || '快照回滚成功')
    fetchVMDetails()
    fetchSnapshots()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '回滚快照失败')
    }
  } finally {
    loading.value = false
  }
}

const fetchSnapshots = async () => {
  if (!currentVM.value) return
  
  try {
    const res = await request.get(`/api/vms/${currentVM.value.id}/snapshots`)
    snapshots.value = res.data.snapshots || []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取快照列表失败')
  }
}

const getActionLabel = (action) => {
  return actionLabels[action] || action
}

const getActionTagType = (action) => {
  return actionColors[action] || ''
}

const fetchVMLogs = async () => {
  if (!currentVM.value) return
  
  try {
    logLoading.value = true
    
    const params = {
      page: logPagination.page,
      size: logPagination.size
    }
    
    if (logFilter.action) {
      params.action = logFilter.action
    }
    
    if (logFilter.status) {
      params.status = logFilter.status
    }
    
    if (logFilter.dateRange && logFilter.dateRange.length === 2) {
      params.start_time = logFilter.dateRange[0] / 1000
      params.end_time = logFilter.dateRange[1] / 1000
    }
    
    const res = await request.get(`/api/vms/${currentVM.value.id}/logs`, { params })
    vmLogs.value = res.data.items || []
    logPagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取操作日志失败')
  } finally {
    logLoading.value = false
  }
}

const handlePageChange = (page) => {
  logPagination.page = page
  fetchVMLogs()
}

const handleSizeChange = (size) => {
  logPagination.size = size
  logPagination.page = 1  // 重置到第一页
  fetchVMLogs()
}

watch(() => migrateForm.targetNode, () => {
  checkTargetNodeResources()
})

onMounted(() => {
  fetchVMList()
  fetchNodesAndISOs()
  
  // 每30秒刷新一次虚拟机列表和指标
  const refreshInterval = setInterval(() => {
    if (!detailDialogVisible.value) {
      fetchVMList()
    }
  }, 30000)
  
  onUnmounted(() => {
    clearInterval(refreshInterval)
  })
})
</script>

<style scoped>
.vm-container {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-bar {
  width: 300px;
}

.resource-info {
  display: flex;
  gap: 15px;
}

.resource-info span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-tabs {
  margin-top: 20px;
}

.monitor-chart {
  width: 100%;
  height: 250px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
  }
  
  .search-bar {
    width: 100%;
  }
}

.log-filter {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.log-filter .el-select,
.log-filter .el-date-editor {
  margin-right: 10px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.el-popover pre {
  margin: 0;
  font-family: monospace;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
